﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Billing.Utilities;
using System.Data;
using Billing.Controls;
using System.Configuration;
using System.Drawing.Printing;

namespace Billing.Windows
{
    public partial class BulkOrderBillingGrid : Window
    {
        public int CreditNoteCompanyID { get; set; }
        public string CreditNoteCompany { get; set; }
        public string BillNo { get; set; }
        public double TotalAmount { get; set; }

        public string PhoneNumberEntered { get; set; }
        public DateTime DeliveryDateEntered { get; set; }
        public string AdditionalDescEntered { get; set; }
        public string CustomerName { get; set; }
        public string DeliveryTime { get; set; }
        public string DeliveryPlace { get; set; }

        public double Advance { get; set; }
        public double Balance { get; set; }

        public double DiscountByCost { get; set; }
        public double DiscountByPercentage { get; set; }
        public string DiscountReason { get; set; }

        // 0 - No Discount
        // 1 - Discount By Cost
        // 2 - Discount By Percentage
        public int DiscountType { get; set; }

        public BulkOrderBillingGrid()
        {
            InitializeComponent();
            lbBillingGrid.Items.Add(new BulkOrderBillingGridItemControl(CreditNoteCompanyID));
            lbBillingGrid.SelectedIndex = 0;
            UpdateBillItemsSlNo();
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            UpdateBillItemsSlNo();
            if (e.Key == Key.Escape)
            {
                if (lbBillingGrid.Items.Count > 0)
                {
                    if (MessageBoxResult.OK == MessageBox.Show("Do you want to close?", "Closing", MessageBoxButton.OKCancel, MessageBoxImage.Question))
                        this.Close();
                }
                else
                    this.Close();
            }
            else if (e.Key == Key.F2)
            {
                BulkOrderDetails detail = new BulkOrderDetails(this, PhoneNumberEntered, DeliveryDateEntered, AdditionalDescEntered, TotalAmount, Advance, DiscountType, DiscountByCost, DiscountByPercentage, DiscountReason, CustomerName, DeliveryTime, DeliveryPlace);
                detail.Owner = this;
                detail.ShowDialog();
                phoneNo.Content = PhoneNumberEntered;
                customerName.Content = CustomerName;
                deliveryDate.Content = DeliveryDateEntered.ToString("dd-MMM-yyyy");
                description.Content = AdditionalDescEntered;
                advanceAmt.Content = Advance;
                deliverytime.Content = DeliveryTime;
                deliveryPlace.Content = DeliveryPlace;
                Balance = 0;
                if (DiscountType == 1)
                {
                    discType.Content = "Discount Amount:";
                    discount.Content = DiscountByCost.ToString();
                    Balance = TotalAmount - Advance - DiscountByCost;
                    if (Balance < 0)
                    {
                        Advance = Advance + Balance;
                        advanceAmt.Content = Advance.ToString();
                        Balance = 0;
                    }
                    balanceAmt.Content = Balance.ToString();
                }
                else
                {
                    discType.Content = "Discount Percentage:";
                    discount.Content = DiscountByPercentage.ToString();
                    Balance = TotalAmount - Advance - ((DiscountByPercentage * TotalAmount) / 100);
                    if (Balance < 0)
                    {
                        Advance = Advance + Balance;
                        advanceAmt.Content = Advance.ToString();
                        balanceAmt.Content = "0";
                    }
                    balanceAmt.Content = Balance.ToString();
                }
            }
        }

        void UpdateBillItemsSlNo()
        {
            try
            {
                int SlNo = 1;
                foreach (BulkOrderBillingGridItemControl itemControl in lbBillingGrid.Items)
                {
                    itemControl.lblSrNo.Content = SlNo++;
                }
            }
            catch (Exception) { }
        }

        BulkOrderBillingGridItemControl GetSelectedItem()
        {
            try
            {
                return lbBillingGrid.SelectedItem as BulkOrderBillingGridItemControl;
            }
            catch (Exception)
            {
                return null;
            }
        }

        private void lbBillingGrid_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter && GetSelectedItem().txtQty.IsFocused)
                {
                    BulkOrderBillingGridItemControl item = (lbBillingGrid.SelectedItem as BulkOrderBillingGridItemControl);
                    double value;
                    if (!(double.TryParse(item.txtQty.Text, out value)))
                    {
                        if (item.txtQty.Text != string.Empty)
                        {
                            MessageBox.Show("Invalid Quantity Field", "Invalid Qty", MessageBoxButton.OK, MessageBoxImage.Error);
                            item.txtQty.Clear();
                        }
                        return;
                    }
                    else
                    {
                        if (item.txtPrice.Tag != null)
                            item.txtPrice.Text = (value * double.Parse(item.txtPrice.Tag.ToString())).ToString();
                    }

                    if (!(SetSelectedIndexForEmptyItem()))
                    {
                        lbBillingGrid.Items.Add(new BulkOrderBillingGridItemControl(CreditNoteCompanyID));
                        SetLastSelectedItem();
                    }
                }
                else if (e.Key == Key.Up)
                {
                    BulkOrderBillingGridItemControl item = lbBillingGrid.SelectedItem as BulkOrderBillingGridItemControl;
                    double value;
                    if (!(double.TryParse(item.txtQty.Text, out value)))
                    {
                        if (item.txtQty.Text != string.Empty)
                        {
                            MessageBox.Show("Invalid Quantity Field", "Invalid Qty", MessageBoxButton.OK, MessageBoxImage.Error);
                            item.txtQty.Clear();
                        }
                        return;
                    }
                    else
                    {
                        if (item.txtPrice.Tag != null)
                            item.txtPrice.Text = (value * double.Parse(item.txtPrice.Tag.ToString())).ToString();
                    }

                    lbBillingGrid.SelectedIndex = lbBillingGrid.SelectedIndex > 0 ? lbBillingGrid.SelectedIndex - 1 : 0;
                    item = lbBillingGrid.SelectedItem as BulkOrderBillingGridItemControl;
                    if (item != null)
                    {
                        item.txtQty.Focus();
                        item.txtQty.SelectAll();
                    }
                }
                else if (e.Key == Key.Down)
                {
                    BulkOrderBillingGridItemControl item = lbBillingGrid.SelectedItem as BulkOrderBillingGridItemControl;
                    double value;
                    if (!(double.TryParse(item.txtQty.Text, out value)))
                    {
                        if (item.txtQty.Text != string.Empty)
                        {
                            MessageBox.Show("Invalid Quantity Field", "Invalid Qty", MessageBoxButton.OK, MessageBoxImage.Error);
                            item.txtQty.Clear();
                        }
                        return;
                    }
                    else
                    {
                        if (item.txtPrice.Tag != null)
                            item.txtPrice.Text = (value * double.Parse(item.txtPrice.Tag.ToString())).ToString();
                    }

                    lbBillingGrid.SelectedIndex = lbBillingGrid.SelectedIndex > -1 ? lbBillingGrid.SelectedIndex + 1 : 0;
                    item = lbBillingGrid.SelectedItem as BulkOrderBillingGridItemControl;
                    if (item != null)
                    {
                        item.txtQty.Focus();
                        item.txtQty.SelectAll();
                    }
                }
                else if (e.Key == Key.Left)
                {
                    BulkOrderBillingGridItemControl item = lbBillingGrid.SelectedItem as BulkOrderBillingGridItemControl;
                    if (item != null)
                    {
                        item.txtCode.Focus();
                        item.txtCode.SelectAll();
                    }
                }
                else if (e.Key == Key.Right)
                {
                    BulkOrderBillingGridItemControl item = lbBillingGrid.SelectedItem as BulkOrderBillingGridItemControl;
                    if (item != null)
                    {
                        item.txtQty.Focus();
                        item.txtQty.SelectAll();
                    }
                }
                else if (e.Key == Key.F1)
                {
                    if (PhoneNumberEntered == null || PhoneNumberEntered == string.Empty)
                    {
                        BulkOrderDetails detail = new BulkOrderDetails(this, PhoneNumberEntered, DeliveryDateEntered, AdditionalDescEntered, TotalAmount, Advance, DiscountType, DiscountByCost, DiscountByPercentage, DiscountReason, CustomerName, DeliveryTime, DeliveryPlace);
                        detail.Owner = this;
                        detail.ShowDialog();
                        phoneNo.Content = PhoneNumberEntered;
                        customerName.Content = CustomerName;
                        deliveryDate.Content = DeliveryDateEntered.ToString("dd-MMM-yyyy");
                        description.Content = AdditionalDescEntered;
                        advanceAmt.Content = Advance;
                        deliverytime.Content = DeliveryTime;
                        deliveryPlace.Content = DeliveryPlace;
                        Balance = 0;
                        if (DiscountType == 1)
                        {
                            discType.Content = "Discount Amount";
                            discount.Content = DiscountByCost.ToString();
                            Balance = TotalAmount - Advance - DiscountByCost;
                            if (Balance < 0)
                            {
                                Advance = Advance + Balance;
                                advanceAmt.Content = Advance.ToString();
                                Balance = 0;
                            }
                            balanceAmt.Content = Balance.ToString();
                        }
                        else
                        {
                            discType.Content = "Discount Percentage";
                            discount.Content = DiscountByPercentage.ToString();
                            Balance = TotalAmount - Advance - ((DiscountByPercentage * TotalAmount) / 100);
                            if (Balance < 0)
                            {
                                Advance = Advance + Balance;
                                advanceAmt.Content = Advance.ToString();
                                balanceAmt.Content = "0";
                            }
                            balanceAmt.Content = Balance.ToString();
                        }
                    }
                    else
                    {
                        SetTotalAmount();

                        new Confirm().ShowDialog();

                        if (Storage.IsValid)
                        {

                            bool isItemsRemoved = false;
                            for (int i = 0; i < lbBillingGrid.Items.Count; i++)
                            {
                                BulkOrderBillingGridItemControl item = lbBillingGrid.Items[i] as BulkOrderBillingGridItemControl;
                                if (item.txtQty.Text == "0" || item.txtQty.Text == string.Empty)
                                {
                                    lbBillingGrid.Items.Remove(lbBillingGrid.Items[i]);
                                    isItemsRemoved = true;
                                    i -= 1;
                                }
                            }
                            if (isItemsRemoved)
                                UpdateBillItemsSlNo();

                            this.BillNo = Database.GenerateBillForBulkOrder(lbBillingGrid.Items, double.Parse(lblFinalPrice.Content.ToString()), PhoneNumberEntered, DeliveryDateEntered, AdditionalDescEntered, Advance.ToString(), Balance.ToString(), DiscountByCost.ToString(), DiscountByPercentage.ToString(), DiscountReason, CustomerName, DeliveryTime, DeliveryPlace, 1, 0, 0);
                            this.TotalAmount = double.Parse(lblFinalPrice.Content.ToString());

                            if (PrintCommon.PrintItems != null)
                                PrintCommon.PrintItems.Clear();
                            if (PrintCommon.CreditNoteItems != null)
                                PrintCommon.CreditNoteItems.Clear();
                            if (PrintCommon.BulkOrderItems != null)
                                PrintCommon.BulkOrderItems.Clear();
                            if (PrintCommon.VendorItems != null)
                                PrintCommon.VendorItems.Clear();

                            foreach (BulkOrderBillingGridItemControl item in lbBillingGrid.Items)
                            {
                                PrintCommon.BulkOrderItems.Add(item);
                            }
                            PrintCommon.TotalAmt = TotalAmount;
                            Storage.IsFirstBill = false;
                            Storage.CreditNoteCompany = string.Empty;
                            Storage.BillNo = this.BillNo;
                            
                            if (ConfigurationManager.AppSettings["PrinterType"] != null && ConfigurationManager.AppSettings["PrinterType"].ToString() == "new")
                            {
                                NewBulkPrinter form = new NewBulkPrinter(Storage.BillNo);
                                form.printDocument1.PrintController = new StandardPrintController();
                                form.printDocument1.Print();
                            }
                            else
                            {
                                OldBulkPrinter form = new OldBulkPrinter(Storage.BillNo);
                                form.printDocument1.PrintController = new StandardPrintController();
                                form.printDocument1.Print();
                            }

                            if (this.BillNo == string.Empty)
                            {
                                MessageBox.Show("Some Exception Has Occurred. Please try again later.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }
                            else
                            {
                                //MessageBox.Show("Bill Generated Successfully.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                                this.Close();
                            }
                        }
                    }
                }
                SetTotalAmount();
            }
            catch (Exception) { }
        }

        private void SetLastSelectedItem()
        {
            try
            {
                lbBillingGrid.SelectedIndex = lbBillingGrid.Items.Count - 1;
            }
            catch (Exception) { }
        }

        private bool SetSelectedIndexForEmptyItem()
        {
            foreach (BulkOrderBillingGridItemControl item in lbBillingGrid.Items)
            {
                if (item.txtCode.Text.ToString() == string.Empty || item.txtQty.Text.ToString() == string.Empty)
                {
                    lbBillingGrid.SelectedItem = item;
                    (lbBillingGrid.SelectedItem as BulkOrderBillingGridItemControl).txtCode.Focus();
                    return true;
                }
            }
            return false;
        }

        private void SetTotalAmount()
        {
            double value = 0;
            foreach (BulkOrderBillingGridItemControl item in lbBillingGrid.Items)
            {
                if (item.txtPrice.Text != string.Empty)
                    value += double.Parse(item.txtPrice.Text);
            }

            this.TotalAmount = value;
            lblFinalPrice.Content = value.ToString();

            if (DiscountType == 0)
            {
                Balance = TotalAmount - Advance;
                balanceAmt.Content = Balance.ToString();
            }
            else if (DiscountType == 1)
            {
                discType.Content = "Discount Amount:";
                discount.Content = DiscountByCost.ToString();
                Balance = TotalAmount - Advance - DiscountByCost;
                if (Balance < 0)
                {
                    Advance = Advance + Balance;
                    advanceAmt.Content = Advance.ToString();
                    Balance = 0;
                }
                balanceAmt.Content = Balance.ToString();
            }
            else
            {
                discType.Content = "Discount Percentage:";
                discount.Content = DiscountByPercentage.ToString();
                Balance = TotalAmount - Advance - ((DiscountByPercentage * TotalAmount) / 100);
                if (Balance < 0)
                {
                    Advance = Advance + Balance;
                    advanceAmt.Content = Advance.ToString();
                    balanceAmt.Content = "0";
                }
                balanceAmt.Content = Balance.ToString();
            }
        }
    }
}
